package com.vaha.application.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.cyber.domain.constant.HttpResultCode;
import com.cyber.domain.entity.AuthingToken;
import com.cyber.domain.exception.BusinessException;
import com.vaha.application.service.LoginService;
import com.vaha.application.service.PasswordService;
import com.vaha.application.service.UserAccountService;
import com.vaha.application.service.UserService;
import com.vaha.domain.entity.User;
import com.vaha.domain.entity.UserAccount;
import com.vaha.infrastructure.event.UserCardEvent;
import lombok.RequiredArgsConstructor;
import me.zhyd.oauth.model.AuthUser;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 登录校验方法
 */
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService<JSONObject> {

    private final UserService userService;

    private final UserAccountService userAccountService;

    private final PasswordService passwordService;

    private final ApplicationContext applicationContext;
//
//    private final LoginInforService loginInforService;

    public static final String UNKNOWN = "unknown";

    /**
     * 登录
     */
    @Override
    public AuthingToken<JSONObject> login(String username, String password) {

        UserAccount userAccount = new UserAccount();
        userAccount.setAccount(username);
        userAccount = userAccountService.selectOne(userAccount);

        if (Objects.isNull(userAccount)) {
            throw new BusinessException("登录账号：" + username + "不存在", HttpResultCode.BAD_AUTH.getCode());
        }
        if (1 == userAccount.getDeleted()) {
//            loginInforService.insertLoginInfor(user.getId(), username, UserConstants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new BusinessException("对不起，您的账号：" + username + "已被删除", HttpResultCode.BAD_AUTH.getCode());
        }
        if (1 == userAccount.getLockd()) {
//            loginInforService.insertLoginInfor(user.getId(), username, UserConstants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new BusinessException("对不起，您的账号：" + username + "已锁定", HttpResultCode.BAD_AUTH.getCode());
        }
        passwordService.validate(userAccount, password);

        User user = new User();
        user.setCode(userAccount.getUserCode());
        // 查询登录用户信息
        user = userService.selectOne(user);
        if (Objects.isNull(user)) {
            throw new BusinessException("登录账号：" + username + "不存在", HttpResultCode.BAD_AUTH.getCode());
        }

        if (1 == user.getDeleted()) {
//            loginInforService.insertLoginInfor(user.getId(), username, UserConstants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new BusinessException("对不起，您的账号：" + username + "已被删除", HttpResultCode.BAD_AUTH.getCode());
        }

        AuthingToken<JSONObject> loginUser = new AuthingToken<>();
        loginUser.setSessionName(user.getName());
        loginUser.setUser(JSONObject.parseObject(JSONObject.toJSONString(user)));

        return loginUser;
    }

    @Override
    public AuthingToken<JSONObject> thirdAuthingCheckAccount(AuthUser authUser, String source) {
        UserAccount userAccount = new UserAccount();
        userAccount.setCode(source + authUser.getUuid());
        userAccount = userAccountService.selectOne(userAccount);

        if (Objects.isNull(userAccount)) {
            userAccount = createThirdAccountAndUser(authUser, source);
        }

        if (1 == userAccount.getLockd()) {
            throw new BusinessException("对不起，您的账号：" + userAccount.getAccount() + "已锁定", HttpResultCode.BAD_AUTH.getCode());
        }

        User user = new User();
        user.setCode(userAccount.getUserCode());
        // 查询登录用户信息
        user = userService.selectOne(user);

        AuthingToken<JSONObject> loginUser = new AuthingToken<>();
        loginUser.setSessionName(user.getName());
        loginUser.setUser(JSONObject.parseObject(JSONObject.toJSONString(user)));

        return loginUser;
    }

    private UserAccount createThirdAccountAndUser(AuthUser authUser, String source) {

        User user = new User();
        user.toEvent(authUser);

        userService.save(user);

        UserAccount userAccount = new UserAccount();
        userAccount.toEvent(authUser, user, source);

        userAccountService.save(userAccount);
        //异步创建卡包
        applicationContext.publishEvent(new UserCardEvent(user.getCode()));
        return userAccount;
    }

    @Override
    public void logout(String userId, String loginName) {
//        loginInforService.insertLoginInfor(userId, loginName, UserConstants.LOGOUT, "退出成功");
    }
}
